package com.gxuwz.medical.web.listener;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

public class MySessionContext {

	private static MySessionContext instance;
	private HashMap<String, HttpSession> sessionMap;

	// 创建存储session的map集合
	private MySessionContext() {
		sessionMap = new HashMap<String, HttpSession>();
	}

	// 获取处理session的实例
	public static MySessionContext getInstance() {
		if (instance == null) {
			instance = new MySessionContext();
		}
		return instance;
	}

	// 添加一个session到map
	public synchronized void addSession(HttpSession session) {
		if (session != null) {
			sessionMap.put(session.getId(), session);
		}
	}

	// 删除一个session到map
	public synchronized void delSession(HttpSession session) {
		if (session != null) {
			sessionMap.remove(session.getId());
		}
	}

	// 根据sessionId获取一个session对象
	public synchronized HttpSession getSession(String sessionID) {
		if (sessionID == null) {
			return null;
		}
		return sessionMap.get(sessionID);
	}

	// 检查是否有存在该用户名的session
	public HttpSession checkExist(String username) {

		Set<Map.Entry<String, HttpSession>> entrySet = sessionMap.entrySet();

		for (Map.Entry<String, HttpSession> entry : entrySet) {
			HttpSession session = entry.getValue();

			Object usernameValue = session.getAttribute("usernameKey");

			if (usernameValue != null && usernameValue.toString().equals(username)) {
				return entry.getValue();
			}
		}

		return null;
	}

}
